﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;

namespace JiuMeiMall.PMethod
{
    /// <summary>
    /// 系统配置，修改配置文件无需重启程序
    /// </summary>
    public static class SysConfig
    {
        /// <summary>
        /// 配置文件最后修改日期
        /// </summary>
        private static DateTime lastWriteTime = DateTime.MinValue;

        /// <summary>
        /// 系统配置节
        /// </summary>
        const string AppSettingsSectionName = "appSettings";

        /// <summary>
        /// 当前系统配置文件
        /// </summary>
        static Configuration localConfig = null;

        static SysConfig()
        {
            localConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        }

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="cfgName">配置名称</param>
        /// <returns></returns>
        public static string GetConfig(string cfgName)
        {
            UpdateAppSettings();
            return ConfigurationManager.AppSettings[cfgName];
        }

        /// <summary>
        /// 修改配置
        /// </summary>
        /// <param name="cfgName">配置名称</param>
        /// <param name="value">设置值</param>
        public static void SetConfig(string cfgName, string value)
        {
            UpdateAppSettings();
            if (ConfigurationManager.AppSettings[cfgName] != value)
            {
                ConfigurationManager.AppSettings.Remove(cfgName);
                ConfigurationManager.AppSettings.Set(cfgName, value);

                localConfig.Save();
            }
        }

        /// <summary>
        /// 及时刷新配置，无需重启程序
        /// </summary>
        private static void UpdateAppSettings()
        {
            DateTime tlastWriteTime = DateTime.MinValue;
            if (File.Exists(localConfig.FilePath))
            {
                tlastWriteTime = File.GetLastWriteTime(localConfig.FilePath);

                if (tlastWriteTime != lastWriteTime)
                {
                    lastWriteTime = tlastWriteTime;
                    ConfigurationManager.RefreshSection(AppSettingsSectionName);
                }
            }
        }
    }
}
